#include"message.h"
#include"timeStamp.h"
#include<iostream>
std::string GetSubStringAfterLastSlash(const std::string &absoluteFileName)
{
    int pos = 0;
    for(int i = absoluteFileName.length() - 1; i >= 0; --i)
    {
        if(absoluteFileName[i] == '/')
        {
            pos = i;
            break;
        }
    }
    return absoluteFileName.c_str() + pos + 1;
}
Message::Message(LOG_LEVEL level,
                 const std::string& absoluteFileName,
                 const std::string& functionName,
                 int lineNumber)
{
    std::string fileName = GetSubStringAfterLastSlash(absoluteFileName);
    m_coloredHeader = FormatHeader(level, fileName, functionName, lineNumber, true);
    m_commonHeader = FormatHeader(level, fileName, functionName, lineNumber, false);
}
std::string Message::formatFieldWithColor(COLOR_NUMBER colorNumber,
                                          bool dark,
                                          const std::string delimiter,
                                          const std::string fieldName,
                                          bool colored)
{
    std::stringstream ss;   // ss << "xxx"
    /* 带颜色 */
    if(colored)ss << "\033[" << dark << ";" << colorNumber << "m";
    /* 字段信息 */
    ss << fieldName;
    /* 后面接日志具体信息，需要重置颜色属性 */
    if(colored)ss << "\033[0m";    //\033[0;  0;是调整深浅的，0m是重置属性的
    /* 分隔符 */
    ss << delimiter;
    return ss.str();
}
std::string Message::FormatHeader(LOG_LEVEL level,
                                  const std::string &fileName,
                                  const std::string &functionName,
                                  int lineNumber,
                                  bool colored)
{
    /* 时间戳 */
    std::stringstream ss;
    ss << formatFieldWithColor(DEFAULT_COLOR, 0, "", TimeStamp::Now().ToString(), colored);
    /* 日志级别 */
    COLOR_NUMBER logLevelColor = LogLevelColor[level];
    std::string logLevelType = LogLevelType[level];
    ss << formatFieldWithColor(logLevelColor, 1, "", logLevelType, colored);
    /* 文件名称 */
    COLOR_NUMBER fileColor = LogFieldColor[FILE_NAME];
    ss << formatFieldWithColor(fileColor, 1, "", "[" + fileName + "]", colored);
    /* 函数名称 */
    COLOR_NUMBER functionColor = LogFieldColor[FUNCTION_NAME];
    ss << formatFieldWithColor(functionColor, 1, "", "[" + functionName + "]", colored);
    /* 行号 */
    COLOR_NUMBER lineColor = LogFieldColor[LINE_NUMBER];
    ss << formatFieldWithColor(lineColor, 1, ": ", "[" + std::to_string(lineNumber) + "]", colored);
    return ss.str();
}
std::string Message::ToString(bool colored) const
{
    return colored ? m_coloredHeader + m_msg : m_commonHeader + m_msg;
}


// #define __TEST__
#ifdef __TEST__
int main()
{
    /* [时间戳][/home/xcg/test/src/logger/message.cc][main][73] */
    Message msg(INFO, __FILE__, __FUNCTION__, __LINE__);
    std::cout << msg.ToString() << std::endl;
}
#endif